package com.xiaoq.shop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4UserCouponVo;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.order.service.IShopOrderService;
import com.xiaoq.shop.entity.SPUReviewEntity;
import com.xiaoq.shop.repository.ISPURepository;
import com.xiaoq.shop.service.ISPUReviewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xinpeng created on 16/9/30-上午10:05.
 */

@Service
public class SPUReviewServiceImpl implements ISPUReviewService {

    private static final Logger logger = LoggerFactory.getLogger(SPUReviewServiceImpl.class);

    @Autowired
    private IShopOrderService orderService;

    @Autowired
    private ISPURepository spuRepository;

    @Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
    private IUserApi userDubboApi;

    @Override
    public boolean commitComment(String userId, String shopId, String orderId, String spuCode, SPUReviewEntity spuReviewEntity) {
        //首先更改订单中当前SKU的评论状态,改为已评论
        int success = orderService.updateReviewStateInOrder(userId, orderId, spuReviewEntity.getSkuCode(), 1, ConstantUtil.ORDER_TICKET_STATUS_HAVA_review);
        //如果更改评论状态成功,则继续发布主评论到商品评论表
        if (success == 1 || success == 2) {
            try {
                UserInfo4UserCouponVo accountDTO = userDubboApi.getUserInfoById(userId);
                spuReviewEntity.setReviewerId(userId);
                spuReviewEntity.setReviewerDisplayImgUrl("");
                //spuReviewEntity.setReviewerRank("");
                spuReviewEntity.setCreatedAt(System.currentTimeMillis());
                spuRepository.addReview2Spu(shopId, spuCode, spuReviewEntity);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error("发表商品评论失败,补偿订单中SKU的评论状态,重新将SKU的评论状态值为未评论");
                try {
                    orderService.callBackReviewState(userId, orderId, spuReviewEntity.getSkuCode(), ConstantUtil.ORDER_TICKET_STATUS_HAVE_PAID);

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("补偿订单中SKU的评论状态失败,请手工恢复此订单中SKU的评论状态,订单号为:【" + orderId + "】,skuCode=【" + spuReviewEntity.getSkuCode() + "】");
                }
            }
            return false;
        }
        return false;
    }
}
